# -- coding: utf-8 --

import urllib
import urllib2
import json
import os
import time
import pymysql
import pymysql.cursors
import datetime

connection = pymysql.connect(host='localhost',
                             user='www_jc8mo4_cn',
                             db='www_jc8mo4_cn',
                             password='3HE3sdAcCjA4kthp',
                             charset='utf8',
                             cursorclass=pymysql.cursors.DictCursor);

def checkDomain(domain):
    requrl = "https://wx.horocn.com/api/v2/wxUrlCheck?api_token=8de190476e3f7c39c305251b25b0abef&req_url="+domain

    try:
        time.sleep(0.5)
        request = urllib2.Request(requrl)
        response = urllib2.urlopen(request,timeout = 3)
        js = json.loads(response.read())
        if js['code'] is 0:
            if  js['data']['err_code'] == 0:
                return True
            else:
                return False
        else:
            print('api error,again domain:'+domain);
            return checkDomain(domain);

    except Exception as e:
        print('error again')
        print(e)
        return  checkDomain(domain);


def main(cursor):
    # 忽略检测超过3次仍然被封的域名
    d = datetime.datetime.now().strftime('%Y-%m-%d')
    sql = "select * from fa_domain where uid in (select uid from fa_user where fa_user.vip_expire_time>'"+d+"') and fa_domain.status!=3 "
    cursor.execute(sql)
    rs = cursor.fetchall()
    for (index,domainObj) in enumerate(rs):
        id = domainObj.get('id')
        domain = domainObj.get('domain')
        status = domainObj.get('status')
        update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if checkDomain(domain):
            # 域名正常
            status = 0
            print(domain+" is ok")
        else:
            print(domain+" is broken")
            status = status+1;
        update_sql = "update fa_domain set status=%d,update_time='%s' where id=%d" % (status,update_time,id)
        rt = cursor.execute(update_sql)
        connection.commit()


cursor = connection.cursor()
n=0
while True:
    startTime = int(time.time())
    print("start...")
    main(cursor)
    n=n+1
    s = int(time.time())-startTime
    print("第%d圈,耗时%d秒" % (n,s))